# backend/services/borrow_service.py
from fastapi import HTTPException
from backend.crud import borrow_crud, book_crud


def borrow_book(db, book_id: int, borrower_id: int):
    # 检查图书状态
    book = book_crud.get_book(db, book_id)
    if not book:
        raise HTTPException(status_code=404, detail="图书不存在")

    if book.status != 1:  # 不是上架状态
        raise HTTPException(status_code=400, detail="图书不可借阅")

    # 创建借阅请求
    return borrow_crud.create_borrow_request(db, book_id, borrower_id)


def approve_borrow(db, record_id: int, lender_id: int):
    record = borrow_crud.approve_borrow_request(db, record_id, lender_id)
    if not record:
        raise HTTPException(status_code=404, detail="借阅记录不存在")

    # 更新图书状态为已借出
    book_crud.update_book_status(db, record.book_id, 2)
    return record


def return_book(db, record_id: int):
    record = borrow_crud.mark_as_returned(db, record_id)
    if not record:
        raise HTTPException(status_code=404, detail="借阅记录不存在")

    # 更新图书状态为上架
    book_crud.update_book_status(db, record.book_id, 1)

    # 检查是否有排队记录
    queue = borrow_crud.get_borrow_queue(db, record.book_id)
    if queue:
        # 通知下一位借阅者
        # 这里实现通知逻辑（如发送消息）
        pass

    return record
